package web.service.innovate.impl;

import cnki.tpi.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import web.bo.Innovate.InnovateDbBo;
import web.common.CutPageBean;
import web.dao.EarthquakeReliefDao;
import web.dao.innovate.InnovateDao;
import web.entity.DbEnum;
import web.entity.DetailEntity;
import web.entity.Innovate.InnovateDbEntity;
import web.mapper.CommonMapper;
import web.service.innovate.InnovateService;
import web.utils.FileUtil;
import web.utils.FileuploadUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Description:
 *
 * @author BaiGe
 * @date: 2022/7/12 19:15
 * @Version 1.0
 */
@Service
@Slf4j
public class InnovateServiceImpl implements InnovateService {
    @Autowired
    private InnovateDao innovateDao;

    @Autowired
    CommonMapper commonMapper;

    @Autowired
    private EarthquakeReliefDao earthquakeReliefDao;

    @Value("${filePath.ExtractFilePath}")
    private String filePath;
    @Value("${filePath.Document}")
    private String DocumentPath;
    @Value("${filePath.WC512filepath}")
    private String WC512filepath;

    //本地期刊PDF
    @Value("${filePath.BDQKPDF}")
    private String localPdf;

    //本地期刊详情PDF
    @Value("${filePath.bdqkxqpath}")
    private String bdqkxqpath;

    /*本地两弹一星书籍-文件路径*/
    @Value("${filePath.ldyxbdfilepath}")
    private String ldyxbdfilepath;

    @Value("${filePath.ldyxcq}")
    private String ldyxcq;
    @Value("${filePath.DJQKPath}")
    private String djqkpath;



    @Override
    public List<InnovateDbEntity> commonSearchTopInnovate(InnovateDbBo innovateDbBo) {
        //设置检索
        String primarySearchSql = this.handlePrimarySearch(innovateDbBo.getSearchType(), innovateDbBo.getSearchValue());
        innovateDbBo.setPrimarySearchSql(primarySearchSql);
        List<InnovateDbEntity> list = innovateDao.commonSearchTopInnovate(innovateDbBo);
        //设置时间格式
        if (!list.isEmpty()) {
            list.forEach(entity -> {
                String formatTime = this.handleTimeFormat(entity.getPushDate());
                entity.setPushDate(formatTime);
            });
        }
        return list;
    }

    @Override
    public CutPageBean<InnovateDbEntity> commonSearchInnovate(InnovateDbBo innovateDbBo) {
        CutPageBean<InnovateDbEntity> cutPage = new CutPageBean<>();
        //设置分页起始下标
        innovateDbBo.setStart(innovateDbBo.getPage(), innovateDbBo.getPageSize());
        //设置检索
        String primarySearchSql = this.handlePrimarySearch(innovateDbBo.getSearchType(), innovateDbBo.getSearchValue());
        innovateDbBo.setPrimarySearchSql(primarySearchSql);

        List<InnovateDbEntity> list = innovateDao.commonSearchInnovateList(innovateDbBo);
        //处理时间格式
        if (!list.isEmpty()) {
            list.forEach(InnovateDbEntity -> {
                String timeFormat = handleTimeFormat(InnovateDbEntity.getPushDate());
                InnovateDbEntity.setPushDate(timeFormat);
            });
        }
        int count = (int) innovateDao.commonSearchInnovateCount(innovateDbBo);
        cutPage.initCutPage(count, innovateDbBo.getPageSize(), list);
        return cutPage;
    }

    @Override
    public CutPageBean<InnovateDbEntity> advSearchInnovate(InnovateDbBo innovateDbBo) {
        innovateDbBo.setStart(innovateDbBo.getPage(), innovateDbBo.getPageSize());
        //处理资源分类
        String sortSql = this.handleSortList(innovateDbBo.getSortCodeList());
        innovateDbBo.setSortCodeSql(sortSql);
        //处理初级检索条件
        String primarySearchSql = this.handlePrimarySearch(innovateDbBo.getSearchType(), innovateDbBo.getSearchValue());
        innovateDbBo.setPrimarySearchSql(primarySearchSql);
        //处理高级检索条件
        String advSearchSql = this.handleAdvSearchList(innovateDbBo.getAdvSearchList());
        innovateDbBo.setAdvSearchSql(advSearchSql);
        //处理更新时间
        innovateDbBo.setTheUpdateDate(innovateDbBo.getUpdateDate());

        //检索结果
        CutPageBean<InnovateDbEntity> cutPage = new CutPageBean<>();
        List<InnovateDbEntity> list = innovateDao.advSearchInnovateList(innovateDbBo);
        //处理时间格式
        if (!list.isEmpty()) {
            list.forEach(entity -> {
                String formatTime = this.handleTimeFormat(entity.getPushDate());
                entity.setPushDate(formatTime);
            });
        }
        int count = (int) innovateDao.advSearchInnovateCount(innovateDbBo);
        cutPage.initCutPage(count, innovateDbBo.getPageSize(), list);
        return cutPage;
    }

    @Override
    public CutPageBean<InnovateDbEntity> commonadvSearch(InnovateDbBo innovateDbBo) {
        innovateDbBo.setStart(innovateDbBo.getPage(), innovateDbBo.getPageSize());
        //处理资源分类
        String sortSql = this.handleSortList(innovateDbBo.getSortCodeList());
        innovateDbBo.setSortCodeSql(sortSql);
        //处理初级检索条件
        String primarySearchSql = this.handlePrimarySearch(innovateDbBo.getSearchType(), innovateDbBo.getSearchValue());
        innovateDbBo.setPrimarySearchSql(primarySearchSql);
        //处理高级检索条件
        String advSearchSql = this.handleAdvSearchList(innovateDbBo.getAdvSearchList());
        innovateDbBo.setAdvSearchSql(advSearchSql);
        //处理更新时间
        innovateDbBo.setTheUpdateDate(innovateDbBo.getUpdateDate());

        //检索结果
        CutPageBean<InnovateDbEntity> cutPage = new CutPageBean<>();
        List<InnovateDbEntity> list = innovateDao.commonadvSearch(innovateDbBo);
        //处理时间格式
        if (!list.isEmpty()) {
            list.forEach(entity -> {
                String formatTime = this.handleTimeFormat(entity.getPushDate());
                entity.setPushDate(formatTime);
            });
        }
        int count = (int) innovateDao.commonadvSearchCount(innovateDbBo);
        cutPage.initCutPage(count, innovateDbBo.getPageSize(), list);
        return cutPage;
    }


    @Override
    public Object commonFileInterface(InnovateDbBo innovateDbBo, HttpServletResponse response) throws IOException, InterruptedException {
        String tableName = innovateDbBo.getTableName();
        String absolutelyPath = "";
        //自建库直接返回fileName type(MYDXWX除外)
        if ("CJFX7911".equals(tableName) || "CJFXLAST".equals(tableName)){

           DetailEntity entity =new  DetailEntity();
            entity.setTableName(tableName);
            entity.setFileName(innovateDbBo.getFileName());
            entity= earthquakeReliefDao.getDocumentDetail(entity);
             String cjnpath=commonMapper.getCdPath(entity.getDiscNumber());
                absolutelyPath= Paths.get(cjnpath,entity.getThname(),innovateDbBo.getFileName())
                        .toString();
                String  newfile=absolutelyPath+".pdf";
                File file = new File(newfile);
                if(!file.exists()){
                    FileUtil.creatbat(absolutelyPath);
                    Thread.sleep(3000);
                    if(file.exists()){
                        FileuploadUtils.download(newfile, response);
                    }
                }
                else {
                    FileuploadUtils.download(newfile, response);
                }





        }
        if ("MYDXTP".equals(tableName) || "MYDXSP".equals(tableName)) {
            InnovateDbEntity innovateDbEntity = innovateDao.indexInnovate(innovateDbBo);
            //处理时间格式
            String formatTime = this.handleTimeFormat(innovateDbEntity.getPushDate());
            innovateDbEntity.setPushDate(formatTime);
            return innovateDbEntity;
            //抓取库 返回全文
        } else if ("MYDXSPIDER_METADATA".equals(tableName)) {
            InnovateDbEntity innovateDbEntity = innovateDao.indexInnovateForGrab(innovateDbBo);
//            返回全文
            return innovateDbEntity.getText();
        } else {
//            MYDXWX库

            if ("MYDXWX".equals(tableName) || "WJMYTS".equals(tableName)) {

                String fileName = innovateDbBo.getFileName();
                if (fileName.endsWith(".nh")) {
                    fileName = fileName.split("\\.")[0] + ".pdf";
                }
                absolutelyPath = DocumentPath + fileName;

            }
            //512地震档案馆
            else  if("512WCDZWXK".equals(tableName)){

                String fileName = innovateDbBo.getNum();
                absolutelyPath = WC512filepath + fileName+ ".pdf";
            }
            else  if("MYDXBDQKXQ".equals(tableName)){

                String fileName = innovateDbBo.getFileName();
               String   repath=fileName.split("_")[0]+"\\PDF\\"+fileName;
                absolutelyPath = bdqkxqpath + repath;
            }
            else  if("LDYXBD".equals(tableName)){
                String fileName = innovateDbBo.getFileName();
                absolutelyPath = ldyxbdfilepath + fileName+ ".pdf";;
            }
            //本地期刊PDF
            else if ("MYDXBDQK".equals(tableName)) {
                absolutelyPath = localPdf + "\\" + innovateDbBo.getSysId() + ".pdf";
            }
            else if(tableName.indexOf("LDYT")>=0){
                String fileName = innovateDbBo.getFileName();
                if (fileName.endsWith(".nh")) {
                    fileName = fileName.split("\\.")[0] + ".pdf";
                } else {
                    fileName = fileName + ".pdf";
                }
                absolutelyPath = ldyxcq  + "\\" + fileName;
            }
            else {  //抽取库
                String folderName = DbEnum.getFolderNameByTableName(innovateDbBo.getTableName());
                String fileName = innovateDbBo.getFileName();
                if (fileName.endsWith(".nh")) {
                    fileName = fileName.split("\\.")[0] + ".pdf";
                } else {
                    fileName = fileName + ".pdf";
                }
                absolutelyPath = filePath + "\\" + folderName + "\\" + fileName;
            }
            HttpServletResponse download = FileuploadUtils.download(absolutelyPath, response);
            return download;
        }
    }


    @Override
    public List<InnovateDbEntity> onlyForTheoryResearch(InnovateDbBo innovateDbBo) {
        return innovateDao.onlyForTheoryResearch(innovateDbBo);
    }

    @Override
    public InnovateDbEntity indexInnovate(String fileName, String tableName, String sysId) {
        InnovateDbEntity innovateDbEntity = new InnovateDbEntity();
        innovateDbEntity.setFileName(fileName);
        innovateDbEntity.setSysId(sysId);
        innovateDbEntity.setTableName(tableName);

        InnovateDbEntity innovate = innovateDao.indexInnovate(innovateDbEntity);
        if (innovate != null) {
            String timeFormat = this.handleTimeFormat(innovate.getPushDate());
            innovate.setPushDate(timeFormat);
        }

        return innovate;
    }

    @Override
    public List<InnovateDbEntity> getCaptureCover(String sortCode, Integer topNum) {
        InnovateDbBo innovateDbBo = new InnovateDbBo();
        innovateDbBo.setTopNum(topNum);
        innovateDbBo.setSortCode(sortCode);
        List<InnovateDbEntity> captureList = innovateDao.getTopCapture(innovateDbBo);
        return captureList;
    }

    /**
     * 处理初级检索集合
     *
     * @param
     * @return
     */
    private String handlePrimarySearch(String searchType, String searchValue) {
        if (!StringUtils.hasLength(searchValue)) {
            return null;
        }
        if ("题名".equals(searchType)||"行业分类代码".equals(searchType)) {
            return searchType + "= '" + searchValue + "'";
        } else if ("作者".equals(searchType) || "主题".equals(searchType)) {
            return searchType + "% '" + searchValue + "'";
        } else {
            return searchType + "= '*" + searchValue + "'";
        }
    }

    /**
     * 处理资源分类集合
     *
     * @param sortCodeList
     * @return
     */
    private String handleSortList(List<String> sortCodeList) {
        if (CollectionUtils.isEmpty(sortCodeList))
            return null;
        StringBuffer bf = new StringBuffer("(");
        String column = "行业分类代码";
        for (String sort : sortCodeList) {
            if (!"".equals(sort) && sort != null) {
                if (sort.split(",").length > 1) {
                    String[] split = sort.split(",");
                    for (int i = 0; i < split.length; i++) {
                        bf.append(column).append(" = ").append(split[i]).append("?").append("  or ");
                    }
                    continue;
                }
                bf.append(column).append(" = ").append(sort).append("?").append("  or ");
            }
        }
        if (bf.length() == 0) {
            return null;
        }
        String returnStr = bf.substring(0, bf.length() - 3) + ")";
        return returnStr;
    }

    /**
     * 处理高级检索集合
     *
     * @param AdvSearchList
     * @return
     */
    private String handleAdvSearchList(List<Map<String, String>> AdvSearchList) {
        if (CollectionUtils.isEmpty(AdvSearchList))
            return null;
        StringBuffer bf = new StringBuffer("(");
        for (int i = 0; i < AdvSearchList.size(); i++) {
            String key = AdvSearchList.get(i).get("key");
            String value = AdvSearchList.get(i).get("value");
            String logic = "";
            if (i < AdvSearchList.size() - 1) {
                logic = AdvSearchList.get(i + 1).get("logic");
            }
            //如果搜索词和搜索选项为空直接进行下一次循环
            if (!StringUtils.hasLength(key) || !StringUtils.hasLength(value)) {
                continue;
            }
            String symbol = this.choiceSymbol(key);
//                bf.append(key).append("='*").append(value).append("'");
            bf.append(key).append(symbol).append(value).append("'");
            //拼and和or
            if (StringUtils.hasLength(logic)) {
                bf.append(" ").append(logic).append(" ");
            }
        }
        if (bf.length() == 0) {
            return null;
        }
        String returnStr = bf + ")";
        //排除空货号的情况
        if ("()".equals(returnStr)) {
            returnStr = "";
        }
        //排除(题名 = 'xxx' or )和(题名 = 'xxx' and )  的情况
        if (returnStr.endsWith("or )")) {
            returnStr = returnStr.replace("or )", ")");
        } else if (returnStr.endsWith("and )")) {
            returnStr = returnStr.replace("and )", ")");
        }
        return returnStr;
    }

    /**
     * 不同的检索词使用不同的语法
     *
     * @param searchType
     * @return
     */
    public String choiceSymbol(String searchType) {
        if ("篇名".equals(searchType) || "题名".equals(searchType)|| "行业分类代码".equals(searchType)) {
            return " = '";
        } else if ("作者".equals(searchType) || "主题".equals(searchType)) {
            return " % '";
        } else {
            return " = '*";
        }
    }

    /**
     * 处理时间格式  将其他格式设置为  yyyy-MM-dd
     *
     * @param time
     * @return
     */
    public String handleTimeFormat(String time) {
        String formatTime = "";
        if (StringUtils.hasLength(time)) {
            String format = "yyyy-MM-dd";
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
            try {
                Date parseTime = simpleDateFormat.parse(time);
                formatTime = simpleDateFormat.format(parseTime);
            } catch (ParseException e) {
//                e.printStackTrace();
                return time;
            }
        }
        return formatTime;
    }

}
